import React, {PropTypes, Component} from 'react';

import {
    Menu,
    Dropdown,
    message,
    Avatar,
    Popconfirm,
    Table,
    Icon,
    Switch,
    Radio,
    Form,
    Row,
    Col,
    Button,
    Checkbox,
    Input,
    Select,
    DatePicker
} from 'antd';

import moment from 'moment';

import API, {SET_FIELD} from 'lib/api';

import {redirect, getLocalTime} from 'lib/utils';

const FormItem = Form.Item;
const Option = Select.Option;
const {RangePicker} = DatePicker;
import Crumb from 'components/Crumb';

import './style.less';
import {handlerPic} from "../../lib/utils";


class Datatable extends Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        let _this = this;
        this.setState({
            loading: true,
        })
        API.fetch(this.props.privs, {}, resp => {
            this.setState({
                privs: resp,
            }, function () {
                API.fetch(_this.props.list, {pagesize: _this.state.pagesize}, resp => {
                    //设置字段配置
                    _this.renderList(resp);

                })
            })
        })


    }


    state = {
        //iconloading
        delIconLoading: false,

        toggleForm: false,

        pagesize: 20,
        //字段配置
        fieldConf: [],

        //列显示
        columns: [],

        //列表数据
        list: [],
        //显示选择列
        showFieldSelect: false,

        //边框
        bordered: true,
        //加载动画

        loading: false,

        privs: {},
        //分页配置:
        pagination: {
            //显示改变页数
            showSizeChanger: true,

            pageSizeOptions: ['10', '20', '30', '50', '100'],

            showQuickJumper: true,
            //显示数据总量和当前数据顺序
            showTotal: function (total, range) {
                return `显示${range[0]}-${range[1]}  共 ${total} 条`
            }
        },
        //选中行
        rowSelection: {},

        //选中id
        selectedRowKeys: []
    }

    /* 渲染列表 */

    renderList(list) {
        let {fields} = list;

        let columns = this.renderColumns(fields);

        list.items.map((v, k) => {
            v.key = v.id;
        })
        //设置字段
        this.setState({
            list: list.items,
            fieldConf: fields,
            columns: columns,
            pagination: {
                pageSize: list.pagesize,
                //默认页
                current: list.page,
                //总数据
                total: list.total
            },
            loading: false
        })
    }

    /* 重新渲染字段列表 */
    renderColumns(fields) {
        let columns = [],
            _this = this;
        fields.map((v, k) => {
            if (v.show) {
                //根据类型不同render不同模型
                let func;
                switch (v.type) {
                    //文本类型
                    case 'text':
                        func = function (text) {
                            return text;
                        }
                        break;
                    //图片类型
                    case 'img':
                        func = function (text) {
                            return <Avatar shape="square" src={handlerPic(text,400)}/>
                        }
                        break;
                    case 'time':
                        func = function (text) {
                            return getLocalTime(text);
                        }
                        break;
                    case 'enum':
                        func = function(text){
                            return v.typedata[text];
                        }
                        break;
                }

                columns.push({
                    title: v.title,
                    dataIndex: v.field,
                    render: func,
                    width: v.width ? v.width : 50,
                    sorter: v.sort ? true : false,
                })
            }
        })

        const {privs} = this.state;
        //操作按钮
        columns.push({
            title: '操作',
            width: 100,
            render: function (text) {
                const menu = (
                    <Menu>

                        {
                            privs.edit
                                ?
                                <Menu.Item>
                                    <a
                                        onClick={_this.handleEdit.bind(_this, text.id)}
                                    >编辑</a>
                                </Menu.Item>
                                : null
                        }

                        {
                            privs.delete
                                ?
                                <Menu.Item>
                                    <Popconfirm
                                        placement="left"
                                        title="确定删除吗?"
                                        onConfirm={_this.handleDeleteRow.bind(_this, text.id)}
                                        okText="确认"
                                        cancelText="取消"
                                    >
                                        <a>删除</a>

                                    </Popconfirm>
                                </Menu.Item>
                                : null
                        }


                    </Menu>
                );
                return <div>
                    <Dropdown overlay={menu} placement="bottomLeft">
                        <Button>
                            <Icon style={{marginRight: 2}} type="bars"/>
                            <Icon type="down"/>
                        </Button>
                    </Dropdown>
                </div>

            }
        })

        return columns;
    }

    //分页触发
    handleChange(pagination, filters, sorter) {

        this.setState({
            loading: true
        })
        let sortby = '';

        if (sorter.field) {
            sortby = sorter.field + ',' + (sorter.order == 'descend' ? 'desc' : 'asc');
        }


        const {current, pageSize} = pagination;
        API.fetch(this.props.list, {page: current, pagesize: pageSize, sortby: sortby}, resp => {
            //设置字段配置
            this.renderList(resp);

        })
    }

    //删除按钮触发
    handleDelete(e, key) {

        const {selectedRowKeys, list} = this.state;

        if (selectedRowKeys.length == 0) {
            message.error("至少选择一条");
            return;
        }

        this.setState({
            delIconLoading: true
        })

        API.fetch(this.state.privs.delete, {model: this.props.model, ids: selectedRowKeys.join(',')}, resp => {
            let newlist = [];
            list.map((v, k) => {
                if (selectedRowKeys.indexOf(v.id) == -1) {
                    newlist.push(v);
                }
            })

            this.setState({
                delIconLoading: false,
                list: newlist,
                selectedRowKeys: [],
            })
        }, err => {
            message.error(err.m);
            this.setState({
                delIconLoading: false,
            })
        })
    }

    handleReload() {
        const {pagination} = this.state;

        this.setState({
            reloadIconLoading: true,
        })

        API.fetch(this.props.list, {page: pagination.current, pagesize: pagination.pageSize}, resp => {
            //设置字段配置
            this.renderList(resp);
            this.setState({
                reloadIconLoading: false,
            })
        })
    }

    //清空已选择列
    handleClear() {
        this.setState({
            selectedRowKeys: [],
        })
    }

    //列选中触发
    handleSelect(selectedRowKeys) {
        this.setState({
            selectedRowKeys: selectedRowKeys
        });
    }


    //列选择展开/收齐
    handleSelectFeildShow() {
        const {showFieldSelect} = this.state;

        this.setState({
            showFieldSelect: !showFieldSelect
        })
    }

    //字段选择
    handleField(k) {
        let {fieldConf} = this.state;

        fieldConf[k].show = !fieldConf[k].show;

        API.fetch(SET_FIELD, {
            model_name: this.props.model,
            field: fieldConf[k].field,
            show: fieldConf[k].show ? 1 : 0
        }, resp => {
            let columns = this.renderColumns(fieldConf);
            this.setState({
                fieldConf: fieldConf,
                columns: columns
            })
        })

    }


    //删除单行

    handleDeleteRow(id) {

        const {list} = this.state;

        API.fetch(this.state.privs.delete, {model: this.props.model, ids: id}, resp => {
            let newlist = [];
            list.map((v, k) => {
                if (v.id != id) {
                    newlist.push(v);
                }
            })

            this.setState({
                list: newlist,
            })
        })
    }


    handleEdit(id) {
        redirect(`${this.state.privs.edit}/${id}`);
    }


    //页面跳转
    handleRedirect(url) {
        redirect(url)
    }

    handleSearch(e) {

        e.preventDefault();

        let _this = this;

        this.setState({
            loading: true,
        })


        let field = this.props.form.getFieldsValue();

        field.pagesize = this.state.pagination.pageSize;

        API.fetch(_this.props.list, field, resp => {
            //设置字段配置
            _this.renderList(resp);

        })


    }

    handleReset(e) {
        this.props.form.resetFields();
    }

    handleToggleForm() {
        const {toggleForm} = this.state;

        this.setState({
            toggleForm: !toggleForm
        })
    }

    render() {
        let {toggleForm, list, fieldConf, columns, showFieldSelect, bordered, loading, rowSelection, selectedRowKeys, pagination} = this.state;
        const {getFieldDecorator} = this.props.form;

        let length = 0;

        rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange: this.handleSelect.bind(this)
        }

        const hasSelected = selectedRowKeys.length > 0;

        return (
            <div>
                <Crumb crumb={this.props.crumb}/>
                <Row gutter={24} style={{borderRadius: '8px', margin: 0, background: '#fff', minHeight: 500}}>
                    <Row>
                        <Form layout="inline" className="searchForm" onSubmit={this.handleSearch.bind(this)}>
                            {
                                fieldConf.map((v, k) => {
                                    if (v.search) {

                                        if (length >= 2 && !toggleForm) {
                                            return;
                                        }

                                        length += 1;

                                        switch (v.searchtype) {
                                            case 'like' :
                                            case 'equal' :

                                                //等于
                                                return (

                                                    <Col key={k} span={8}>

                                                        {getFieldDecorator(v.field, {
                                                            initialValue: ''
                                                        })(
                                                            <Input className="equal"
                                                                   placeholder={v.describe ? v.describe : v.title}/>
                                                        )}

                                                    </Col>

                                                )
                                                break;

                                            case 'enum':
                                                return (
                                                    <Col key={k} span={8}>
                                                        <label style={{marginRight: 10}}>{v.title}</label>
                                                        {getFieldDecorator(v.field, {
                                                            initialValue: '',
                                                        })(
                                                            <Select style={{width: '85%'}}>
                                                                {
                                                                    v.searchdata.map((v, k) => {
                                                                        return (
                                                                            <Option key={k}
                                                                                    value={v.id}>{v.name}</Option>
                                                                        )
                                                                    })
                                                                }

                                                            </Select>
                                                        )}
                                                    </Col>

                                                )
                                                break;
                                            case 'time':

                                                return (
                                                    <Col key={k} span={8}>
                                                        <label style={{marginRight: 10}}>{v.title}</label>
                                                        {getFieldDecorator(v.field, {
                                                            initialValue: ''
                                                        })(
                                                            <RangePicker
                                                                showTime={{
                                                                    hideDisabledOptions: true,
                                                                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                                                                }}
                                                            />
                                                        )}
                                                    </Col>
                                                )

                                                break;
                                        }

                                    }
                                })
                            }

                            {
                                length > 0
                                    ?
                                    <Col span={8}>
                                        <Col span={4}>
                                            <Button type="primary" htmlType="submit">搜索</Button>
                                        </Col>
                                        <Col span={4}>
                                            <Button onClick={this.handleReset.bind(this)}>重置</Button>
                                        </Col>
                                        {
                                            length >= 2
                                                ?
                                                <Col span={4} style={{lineHeight: '28px'}}>
                                                    <a style={{marginLeft: 8}}
                                                       onClick={this.handleToggleForm.bind(this)}>
                                                        {toggleForm ? "收起" : "展开"} <Icon
                                                        type={toggleForm ? 'up' : 'down'}/>
                                                    </a>
                                                </Col>
                                                : ''
                                        }

                                    </Col>
                                    : ''
                            }

                        </Form>
                    </Row>
                    <Row className="head_button" style={{marginTop: 13}} gutter={4}>
                        {
                            this.state.privs.add
                                ?
                                <Button
                                    type="primary"
                                    icon="plus-circle-o"
                                    onClick={this.handleRedirect.bind(this, this.state.privs.add)}
                                >
                                    新增
                                </Button>
                                :
                                ''
                        }

                        {
                            this.state.privs.delete
                                ?
                                <Popconfirm
                                    placement="bottom"
                                    title={"确认删除选中的" + selectedRowKeys.length + '条吗'}
                                    onConfirm={this.handleDelete.bind(this)}
                                    okText="确认"
                                    cancelText="取消"
                                >
                                    <Button
                                        type="primary"
                                        icon="delete"
                                        loading={this.state.delIconLoading}
                                    >
                                        删除
                                    </Button>
                                </Popconfirm>

                                :
                                ''
                        }


                        <Button
                            type="primary"
                            icon="bars"
                            onClick={this.handleSelectFeildShow.bind(this)}
                        >
                            选择列
                        </Button>


                        <Button
                            type="primary"
                            icon="reload"
                            loading={this.state.reloadIconLoading}
                            onClick={this.handleReload.bind(this)}
                        >
                            刷新
                        </Button>


                    </Row>


                    {/* 选择列显示 */}
                    {showFieldSelect
                        ?
                        <Row className="field">
                            {

                                fieldConf.map((v, k) => {
                                    return (
                                        <Col key={k} span={3}>
                                            <Checkbox onChange={this.handleField.bind(this, k)} checked={v.show}
                                                      value={k}>{v.title}</Checkbox>
                                        </Col>
                                    )
                                })
                            }

                            <Col span={3}><Button onClick={this.handleSelectFeildShow.bind(this)}
                                                  type="primary">收起</Button></Col>
                        </Row>
                        :
                        ''

                    }
                    {/* 后台字段显示 */}

                    {hasSelected
                        ?
                        <Row style={{marginBottom: 10, display: 'flex', justifyContent: 'flex-end'}}>
                            <span style={{marginRight: 10, lineHeight: '30px'}}>已选择 {selectedRowKeys.length} 条</span>

                            <Popconfirm
                                placement="left"
                                title="清空已选中行吗?"
                                onConfirm={this.handleClear.bind(this)}
                                okText="确认"
                                cancelText="取消"
                            >
                                <Button type="primary">清空</Button>
                            </Popconfirm>

                        </Row>
                        :
                        ''
                    }

                    <Row>
                        <Table bordered={bordered}
                               loading={loading}
                               onChange={this.handleChange.bind(this)}
                               columns={columns}
                               dataSource={list}
                               pagination={pagination}
                               rowSelection={rowSelection}
                        />
                    </Row>
                </Row>
            </div>
        )

    }

}

export default Form.create()(Datatable);